﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using blackhouse.BlackApart.Business.Places;
using blackhouse.Locations;

namespace blackhouse.BlackApart.Web.Modules {
	public partial class ImportantPlacesItemTemplate : System.Web.UI.UserControl {

		#region Fields

		private PlaceDistance distancer;
		private string distanceFormat;
		private double speed;

		#endregion

		#region Event Handlers

		protected override void OnInit(EventArgs e) {
			base.OnInit(e);

			this.rptPlaces.ItemCreated += new RepeaterItemEventHandler(rptPlaces_ItemCreated);
		}

		#endregion

		#region Methods

		void rptPlaces_ItemCreated(object sender, RepeaterItemEventArgs e) {

			if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
				IPlace place = e.Item.DataItem as IPlace;
				ITextControl ltlDistance = e.Item.FindControl("ltlDistance") as ITextControl;
				if (ltlDistance != null) ltlDistance.Text = string.Format(this.distanceFormat, this.distancer.GetDistance(place));

				ITextControl ltlSpeed = e.Item.FindControl("ltlSpeed") as ITextControl;
				if (ltlSpeed != null) ltlSpeed.Text = string.Format("{0:F0} min.", this.distancer.GetSpeed(place, speed));

				ITextControl ltlName = e.Item.FindControl("ltlName") as ITextControl;
				if (ltlName != null) ltlName.Text = place.Name;

				ITextControl ltlAddress = e.Item.FindControl("ltlAddress") as ITextControl;
				if (ltlAddress != null) ltlAddress.Text = place.Address;

				ITextControl ltlDescription = e.Item.FindControl("ltlDescription") as ITextControl;
				if (ltlDescription != null) ltlDescription.Text = place.Description;

				ITextControl ltlCategory = e.Item.FindControl("ltlCategory") as ITextControl;
				if (ltlCategory != null) ltlCategory.Text = place.Category;

			}
		}

		public void PopulateControl(IEnumerable<IPlace> places, PlaceDistance distancer, string distanceFormat, double speed) {
			this.distancer = distancer;
			this.distanceFormat = distanceFormat;
			this.speed = speed;
			this.rptPlaces.DataSource = places;
			this.rptPlaces.DataBind();
		}

		#endregion

	}
}